package com.ukefu.webim.util.router;

import java.io.File;
import java.io.FileInputStream;
import java.net.URL;

import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.safety.Whitelist;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import com.ukefu.core.UKDataContext;
import com.ukefu.util.UKTools;
import com.ukefu.util.WechatUtils;
import com.ukefu.webim.util.weixin.config.WechatMpConfiguration;
import com.ukefu.webim.web.model.MessageOutContent;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;

@Component
public class WeiXinOutMessageRouter implements OutMessageRouter{

	private WechatMpConfiguration mpconfig = WechatMpConfiguration.getInstance();
	
	@Bean(name="weixin")
	public WeiXinOutMessageRouter initWebIMessageRouter(){
		return new WeiXinOutMessageRouter() ;
	}
	@Override
	public void handler(String touser, String msgtype, String snsid,
			MessageOutContent outMessage) {
		WxMpKefuMessage message = null ;
		try {
			if(UKDataContext.MediaTypeEnum.TEXT.toString().equals(outMessage.getMessageType())){
				String content = WechatUtils.ucKeFufaceTowechat(outMessage.getMessage()) ;
				if(!StringUtils.isBlank(content)) {
					Document document = Jsoup.parse(content) ;
					document.select("p").prepend("") ;
					document.select("br").prepend("") ;
					
					content =  Jsoup.clean(document.html(), "",
							Whitelist.none(), new Document.OutputSettings().prettyPrint(false)); 
					content = content.replaceAll("[\\s]*\n[\\s]*", "\n") ;
					if(content.startsWith("\n")) {
						content = content.replaceFirst("\n", "") ;
					}
					if(content.endsWith("\n")) {
						content = content.substring(0 , content.lastIndexOf("\n"));
					}
				}
				message = WxMpKefuMessage.TEXT().toUser(touser).content(content).build();
			}else if(UKDataContext.MediaTypeEnum.IMAGE.toString().equals(outMessage.getMessageType())){
				String url = UKTools.getSystemConfig().getIconstr() ;
				if(UKTools.getSystemConfig().getIconstr()==null) {
					url = "" ;
				}
				WxMediaUploadResult res = null ;
				File imageFile = new File(UKDataContext.systemFilePath , "upload/"+outMessage.getAttachmentid()+"_original") ;
				if(imageFile.exists()) {
					FileInputStream inputStream = new FileInputStream(imageFile) ;
					res = mpconfig.getConfiguration(snsid).getService().getMaterialService().mediaUpload(WxConsts.MediaFileType.IMAGE, UKDataContext.WxMpFileType.PNG.toString(), inputStream);
				}else {
					res = mpconfig.getConfiguration(snsid).getService().getMaterialService().mediaUpload(WxConsts.MediaFileType.IMAGE, UKDataContext.WxMpFileType.PNG.toString(), new URL(url+outMessage.getMessage()+"_original").openStream());
				}
				message = WxMpKefuMessage.IMAGE().toUser(touser).mediaId(res.getMediaId()).build();
			}
			if(mpconfig.getConfiguration(snsid)!=null && message!=null){
				mpconfig.getConfiguration(snsid).getService().getKefuService().sendKefuMessage(message) ;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
